<template>
  <div class="p-6 space-y-6">
    <!-- 页面标题 -->
    <div class="flex items-center justify-between">
      <h2 class="text-2xl font-bold text-gray-900 dark:text-gray-200">权限管理</h2>
      <button @click="showAddDialog = true" class="btn-primary flex items-center gap-2">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
        新增权限
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="card">
      <div class="flex items-center gap-4">
        <div class="flex-1">
          <input v-model="searchQuery" type="text" placeholder="搜索权限名称..." class="input" />
        </div>
        <select v-model="moduleFilter" class="input w-40">
          <option value="">全部模块</option>
          <option value="user">用户管理</option>
          <option value="role">角色管理</option>
          <option value="system">系统管理</option>
          <option value="content">内容管理</option>
        </select>
        <button @click="searchPermissions" class="btn-primary">搜索</button>
        <button @click="resetSearch" class="btn-secondary">重置</button>
      </div>
    </div>

    <!-- 权限列表 -->
    <div class="card">
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-gray-200 dark:border-gray-700">
              <th class="table-header">权限信息</th>
              <th class="table-header">模块</th>
              <th class="table-header">类型</th>
              <th class="table-header">状态</th>
              <th class="table-header">创建时间</th>
              <th class="table-header">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="permission in filteredPermissions" :key="permission.id" class="table-row">
              <td class="table-cell">
                <div class="flex items-center gap-3">
                  <div
                    class="w-10 h-10 bg-gradient-to-br from-green-500 to-blue-600 rounded-lg flex items-center justify-center">
                    <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                    </svg>
                  </div>
                  <div>
                    <p class="font-medium text-gray-900 dark:text-gray-200">{{ permission.name }}</p>
                    <p class="text-sm text-gray-600 dark:text-gray-400">{{ permission.description }}</p>
                  </div>
                </div>
              </td>
              <td class="table-cell">
                <span class="badge-primary">{{ permission.module }}</span>
              </td>
              <td class="table-cell">
                <span
                  :class="[
                    'badge',
                    permission.type === 'menu'
                      ? 'badge-info'
                      : permission.type === 'button'
                        ? 'badge-warning'
                        : 'badge-primary',
                  ]">
                  {{ getTypeText(permission.type) }}
                </span>
              </td>
              <td class="table-cell">
                <span :class="['badge', permission.status === 'active' ? 'badge-success' : 'badge-danger']">
                  {{ permission.status === 'active' ? '启用' : '禁用' }}
                </span>
              </td>
              <td class="table-cell text-gray-900 dark:text-gray-200">{{ permission.createTime }}</td>
              <td class="table-cell">
                <div class="flex items-center gap-2">
                  <button @click="editPermission(permission)" class="btn-secondary btn-sm">编辑</button>
                  <button
                    @click="togglePermissionStatus(permission)"
                    :class="[
                      'btn-sm rounded px-3 py-1 transition-colors',
                      permission.status === 'active'
                        ? 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 hover:bg-red-200 dark:hover:bg-red-800'
                        : 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 hover:bg-green-200 dark:hover:bg-green-800',
                    ]">
                    {{ permission.status === 'active' ? '禁用' : '启用' }}
                  </button>
                  <button @click="deletePermission(permission)" class="btn-danger btn-sm">删除</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Element Plus 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalPermissions"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination" />
      </div>
    </div>

    <!-- 新增/编辑权限弹窗 -->
    <el-dialog v-model="showAddDialog" :title="editingPermission ? '编辑权限' : '新增权限'" width="500px">
      <form @submit.prevent="savePermission" class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">权限名称</label>
          <input v-model="permissionForm.name" type="text" class="input" required />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">权限描述</label>
          <textarea v-model="permissionForm.description" rows="3" class="input resize-none"></textarea>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">所属模块</label>
          <select v-model="permissionForm.module" class="input" required>
            <option value="">请选择模块</option>
            <option value="user">用户管理</option>
            <option value="role">角色管理</option>
            <option value="system">系统管理</option>
            <option value="content">内容管理</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">权限类型</label>
          <select v-model="permissionForm.type" class="input" required>
            <option value="">请选择类型</option>
            <option value="menu">菜单权限</option>
            <option value="button">按钮权限</option>
            <option value="api">接口权限</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">状态</label>
          <select v-model="permissionForm.status" class="input">
            <option value="active">启用</option>
            <option value="inactive">禁用</option>
          </select>
        </div>
      </form>
      <template #footer>
        <div class="flex justify-end gap-3">
          <button @click="showAddDialog = false" class="btn-secondary">取消</button>
          <button @click="savePermission" class="btn-primary">保存</button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="system-permission">
import { ref, computed } from 'vue'

defineOptions({ name: 'permission' })

const searchQuery = ref('')
const moduleFilter = ref('')
const showAddDialog = ref(false)
const editingPermission = ref<any>(null)
const currentPage = ref(1)
const pageSize = ref(10)
const totalPermissions = ref(200)

const permissionForm = ref({
  name: '',
  description: '',
  module: '',
  type: '',
  status: 'active',
})

// 模拟权限数据
const permissions = ref([
  {
    id: 1,
    name: 'user:view',
    description: '查看用户列表',
    module: '用户管理',
    type: 'menu',
    status: 'active',
    createTime: '2023-01-01 00:00:00',
  },
  {
    id: 2,
    name: 'user:add',
    description: '新增用户',
    module: '用户管理',
    type: 'button',
    status: 'active',
    createTime: '2023-01-01 00:00:00',
  },
  {
    id: 3,
    name: 'role:manage',
    description: '角色管理',
    module: '角色管理',
    type: 'menu',
    status: 'active',
    createTime: '2023-01-01 00:00:00',
  },
  {
    id: 4,
    name: 'system:config',
    description: '系统配置',
    module: '系统管理',
    type: 'menu',
    status: 'active',
    createTime: '2023-01-01 00:00:00',
  },
])

const filteredPermissions = computed(() => {
  let result = permissions.value

  if (searchQuery.value) {
    result = result.filter(
      (permission) =>
        permission.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        permission.description.toLowerCase().includes(searchQuery.value.toLowerCase()),
    )
  }

  if (moduleFilter.value) {
    result = result.filter((permission) => permission.module === moduleFilter.value)
  }

  return result
})

function getTypeText(type: string) {
  const typeMap = {
    menu: '菜单权限',
    button: '按钮权限',
    api: '接口权限',
  }
  return typeMap[type as keyof typeof typeMap] || type
}

function searchPermissions() {
  console.log('搜索权限:', searchQuery.value)
}

function resetSearch() {
  searchQuery.value = ''
  moduleFilter.value = ''
}

function editPermission(permission: any) {
  editingPermission.value = permission
  permissionForm.value = { ...permission }
  showAddDialog.value = true
}

function savePermission() {
  if (editingPermission.value) {
    // 更新权限
    const index = permissions.value.findIndex((p) => p.id === editingPermission.value!.id)
    if (index !== -1) {
      permissions.value[index] = { ...permissions.value[index], ...permissionForm.value }
    }
  } else {
    // 新增权限
    const newPermission = {
      id: Date.now(),
      ...permissionForm.value,
      createTime: new Date().toLocaleString(),
    }
    permissions.value.push(newPermission)
  }

  showAddDialog.value = false
  editingPermission.value = null
  permissionForm.value = { name: '', description: '', module: '', type: '', status: 'active' }
}

function togglePermissionStatus(permission: any) {
  permission.status = permission.status === 'active' ? 'inactive' : 'active'
}

function deletePermission(permission: any) {
  if (confirm('确定要删除这个权限吗？')) {
    permissions.value = permissions.value.filter((p) => p.id !== permission.id)
  }
}

function handleSizeChange(size: number) {
  pageSize.value = size
  currentPage.value = 1
}

function handleCurrentChange(page: number) {
  currentPage.value = page
}
</script>

<style scoped>
.custom-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: rgb(107 114 128);
  --el-pagination-border-radius: 8px;
  --el-pagination-button-color: rgb(107 114 128);
  --el-pagination-button-bg-color: transparent;
  --el-pagination-button-disabled-color: rgb(156 163 175);
  --el-pagination-button-disabled-bg-color: transparent;
  --el-pagination-hover-color: rgb(59 130 246);
  --el-pagination-hover-bg-color: rgb(239 246 255);
}

.dark .custom-pagination {
  --el-pagination-text-color: rgb(156 163 175);
  --el-pagination-button-color: rgb(156 163 175);
  --el-pagination-hover-color: rgb(96 165 250);
  --el-pagination-hover-bg-color: rgb(30 58 138);
}
</style>
